﻿using System;
using System.Collections.Generic;
using Engine;
using Game;
using GameEntitySystem;

using TemplatesDatabase;

public class ComponentSummoner : Component
{
    public List<ComponentSummonee> m_summonees = new List<ComponentSummonee>();

    public SubsystemSummon m_subsystemSummon;

    public ComponentBody m_target;

    public ComponentCreatureModel m_creatureModel;

    public Game.Random m_random = new Game.Random();

    public ulong m_ID;

    public Vector3 Position => m_creatureModel.EyePosition;

    public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
    {
        Load(valuesDictionary, idToEntityMap);
        m_subsystemSummon = Project.FindSubsystem<SubsystemSummon>(true);
        m_creatureModel = Entity.FindComponent<ComponentCreatureModel>(true);
        if (valuesDictionary != null)
        {
            m_ID = valuesDictionary.GetValue<ulong>("ID", ((ulong)m_random.UInt() << 32) + (ulong)m_random.Int());
        }
        m_subsystemSummon.m_summoners.Add(this);
    }

    public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
    {
        valuesDictionary.SetValue<ulong>("ID", m_ID);
        base.Save(valuesDictionary, entityToIdMap);
    }

    public void Summon(Entity entity, Vector3 position)
    {
        ComponentSummonee obj = entity.FindComponent<ComponentSummonee>();
        if (obj == null)
        {
            throw new Exception("无法调用实体，因为它没有ComponentSummonee");
        }

        obj.Position = position;
        obj.m_lord = this;
        obj.m_lordID = m_ID;
        Project.AddEntity(entity);

        var followBehavior = entity.FindComponent<ComponentSummoneeFollowBehavior>();
        if (followBehavior != null)
        {
            followBehavior.LoadLord();
        }
    }
}
